<template>
  <div class="login-container">
    <vue-particles
      color="#fff"
      :particleOpacity="0.7"
      :particlesNumber="60"
      shapeType="circle"
      :particleSize="4"
      linesColor="#fff"
      :linesWidth="1"
      :lineLinked="true"
      :lineOpacity="0.4"
      :linesDistance="150"
      :moveSpeed="2"
      :hoverEffect="true"
      hoverMode="grab"
      :clickEffect="true"
      clickMode="push"
      class="lizi"
    >
    </vue-particles>
    <video src="../../assets/2.mp4" muted autoplay loop></video>
    <div class="mark animate__animated animate__fadeInDown">
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="60px"
        class="login"
      >
        <el-form-item>
          <h1>CHUZI</h1>
        </el-form-item>
        <el-form-item label="用户名" prop="username" placeholder="请输入用户名">
          <el-input
            type="text"
            v-model="form.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" placeholder="请输入密码">
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item class="captcha" prop="captcha" label="验证码">
          <el-input
            placeholder="验证码"
            type="text"
            v-model="form.captcha"
            @keyup.enter.native="submitForm('ruleForm')"
          >
          </el-input>
          <el-button v-html="captchaSvg" @click="shuaxin">获取验证码</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 登录逻辑
// 1 收集用户输入的username 和 password 传递给后端
// 2 登入通过后 将后端返回的token存到本地 跳转主页
// 3 每次请求的时候 携带token到请求头authorization
// 4 展示token校验正确数据
// 5 校验不通过跳转到登录页
import allRoutes from "@/router/allRoutes";
import recursionRoutes from "@/utils/recursionRoutes";
import { getCaptcha, verifyCaptcha, login, getMenuList } from "@/api";
export default {
  data() {
    var validateUsername = (rule, value, callback) => {
      let regExp = /^[a-zA-Z0-9_-]{1}([a-zA-Z0-9]|[._-]){2,15}$/;
      if (regExp.test(value)) {
        callback();
      } else {
        callback(new Error("请输入3-16位用户名(字母,数字,下划线,减号)"));
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入正确的密码"));
      } else {
        callback();
      }
    };

    // 检验验证码
    var validateCaptcha = (rule, value, callback) => {
      if (value === "" || value.length !== 5) {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      captchaSvg: "", //从服务器获取下来的验证码svg结构
      form: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getCaptchaCode();
  },
  methods: {
    // 刷新验证码
    shuaxin() {
      this.getCaptchaCode();
    },
    //   获取验证码
    getCaptchaCode() {
      getCaptcha().then((res) => {
        // console.log(res);
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //代表本地校验通过
          // 加载动画
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          // 先验证验证码是否正确 如果正确在发送登录请求
          verifyCaptcha(this.form.captcha).then((res) => {
            // console.log(res);
            if (res.data.state) {
              let { username, password } = this.form;
              login(username, password).then((res) => {
                console.log("登录成功", res);
                loading.close();
                if (res.data.state) {
                  //  用户名密码正确
                  let { permission, token, userInfo } = res.data;
                  // 存储token
                  localStorage.setItem("qq-token", token);
                  localStorage.setItem("qq-userInfo", JSON.stringify(userInfo));
                  localStorage.setItem(
                    "qq-permission",
                    JSON.stringify(permission)
                  );
                  // 将用户信息存储到vuex中
                  this.$store.commit("SET_USERINFO", userInfo);
                  this.$store.commit("SET_PERMISSION", permission);

                  // 获取用户的权限菜单
                  // getMenuList()
                  // .then(res => {
                  //   // console.log(res.data);
                  //   recursionRoutes(res.data.menuList,allRoutes)
                  // })
                  // 触发vuex中的请求
                  this.$store.dispatch("FETCH_MENULIST").then(() => {
                    console.log(111);
                  });

                  // 跳转到首页
                  this.$router.push("/");
                } else {
                  this.$message.error("用户名或密码错误");
                }
              });
            } else {
              // 错误之后刷新验证码
              this.getCaptchaCode();
              // 错误提示
              this.$message.error("验证码错误哦.");
              // 关闭loading
              loading.close();
            }
          });
        } else {
          console.log("error submit!!!");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .lizi {
    background-size: cover;
    position: absolute;
    z-index: 10;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
  .mark {
    width: 400px;
    height: 400px;
    background: rgba(0, 0, 0, 0.4);
    position: absolute;
    left: 65%;
    top: 35%;
    z-index: 100;
    .el-form {
      width: 350px;
      .el-input {
        margin-bottom: 5px;
      }
      h1 {
        font-size: 34px;
        text-align: center;
        color: #fff;
      }
      .el-button {
        width: 100%;
        background: linear-gradient(90deg, rgb(137, 26, 41), #973a43);
      }
      .captcha {
        vertical-align: top;
        .el-input {
          width: 150px;
          height: 55px;
          vertical-align: top;
          display: inline-block;
        }
        .el-button {
          vertical-align: top;
          display: inline-block;
          width: 140px;
          height: 44px;
          padding: 0;
        }
      }
    }
  }
}
</style>
